package com.dandelion.framework.resolver;


import cn.hutool.json.JSONUtil;
import com.dandelion.business.entity.vo.login.resp.LoginUserInfo;
import com.dandelion.business.entity.vo.user.CurrentUser;
import com.dandelion.framework.annotations.CUAnnotation;
import com.dandelion.framework.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 当前用户解析器
 *
 * @author 77088
 * @date 2022/02/16
 */
@Component
@Slf4j
public class CurrentUserResolver implements HandlerMethodArgumentResolver {


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(CurrentUser.class)
                && parameter.hasParameterAnnotation(CUAnnotation.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {
        String accessToken = nativeWebRequest.getHeader("accessToken");
        try {
            Claims claims = JwtUtil.parseJWT(accessToken);
            String subject = claims.getSubject();
            LoginUserInfo info = JSONUtil.toBean(subject, LoginUserInfo.class);
            Long userId = info.getUserId();
            return new CurrentUser(userId);
        } catch (Exception e) {
            log.warn("token解析异常");
        }
        return null;
    }
}
